<template>
  <div
    class="flex py-2 pl-2 pr-2 justify-center items-center rounded-md border-base-card after:rounded-md gap-4 w-full bg-background-01 black:bg-background-01-dark text-text-01 black:text-text-01-dark"
  >
    <div class="nav-list w-[920px] flex flex-wrap select-none" ref="navListRef">
      <div
        class="nav-item w-[131px] relative bg-background-02 black:bg-background-02-dark hover:bg-background-04 black:hover:bg-background-04-dark h-7 text-center cursor-pointer border-base flex justify-center items-center text-sm"
        v-for="item in navList"
        :key="item.id"
        @click="selectPage(item)"
        :class="{ active: item.active }"
      >
        <el-icon
          class="left-1 cursor-pointer absolute rounded-sm black:hover:bg-background-10-dark hover:bg-background-10"
          @click.stop="showTools(item)"
          :class="{ 'hover:bg-background-11 black:hover:bg-background-11-dark': item.active }"
        >
          <DragIcon />
        </el-icon>
        <span
          class="border-base absolute after:rounded px-1 py-[3px] z-10 rounded flex justify-center items-center gap-[2px] left-0 -top-[30px] bg-background-01 black:bg-background-01-dark text-text-01 black:text-text-01-dark"
          v-show="item.hover"
        >
          <el-tooltip effect="customized" placement="top" content="重命名">
            <el-icon
              class="tab-tool w-[22px] h-[22px]"
              @click="editPanelTitle(item)"
              v-track:click="{
                id: 'thspc_f10_copilot_nav_tool',
                action: 'click',
                logmap: () => ({ type: 'rename', content: item.id })
              }"
              ><PanelTitleEdit
            /></el-icon>
          </el-tooltip>

          <el-tooltip effect="customized" placement="top" content="恢复默认">
            <el-icon
              class="tab-tool w-[22px] h-[22px]"
              @click="selectPage(item, true), (item.hover = false)"
              v-track:click="{
                id: 'thspc_f10_copilot_nav_tool',
                action: 'click',
                logmap: () => ({ type: 'reset', content: item.id })
              }"
              ><PanelReset
            /></el-icon>
          </el-tooltip>
        </span>
        <span class="truncate w-[98px]" v-if="!item.edit">{{ item.title }}</span>
        <input
          :ref="`${item.id}tabInput`"
          v-else
          type="text"
          :autofocus="true"
          class="w-full h-full text-text-01 black:text-text-01-dark text-center z-10 focus:outline-1 focus:outline focus:outline-border-04 black:focus:outline-border-04-dark"
          :value="item.title"
          @blur="savePanelTitle($event, item)"
          @keydown.enter="item.edit = false"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance, h, nextTick, onMounted, ref, type Ref } from 'vue'
import { DragIcon, PanelReset, PanelTitleEdit } from '@/components/icons'
import Sortable, { type SortableEvent } from 'sortablejs'
import { getNavList, resetPanel, updateNavList, updatePanelTitle } from '../services/chat-api'
import { usePanelStore } from '@/stores/panel'
import type { NavListTab } from '@/common/models/aigc-fix-panel'
import { getEventBus } from '@/common/services/chat-event-bus'
import { onClickOutside } from '@vueuse/core'
import { useAppInfoStore } from '@/stores/app'
import { ElMessage, ElMessageBox, type Action } from 'element-plus'
import { ERRORTYPE } from '@/common/config/const'

// 导航栏Dom元素
const navListRef: any = ref(null)

const { proxy } = getCurrentInstance() || {}

// 原始导航列表数据 mock
const navList: Ref<NavListTab[]> = ref([])

// 存储操作后列表 用户展示恢复和数据上传
const localNavList = ref(Array.from(navList.value))

// 拖拽tab实例
const sortable: Ref<Sortable | null> = ref(null)

const { pageChangeEventBus } = getEventBus()

const stockInfo: Ref<{ code: string; name: string }> = ref({ code: '', name: '' })

const preNavListTab: Ref<NavListTab | null> = ref(null)

const appStore = useAppInfoStore()

// 交互：点击外部输入框样式重置
onClickOutside(navListRef, () => {
  navList.value.forEach((navTab) => {
    navTab.hover = false
  })
})

const setNavListData = async () => {
  const storeTabIndex = localStorage.getItem('aif10-tabIndex')
  const tabIndex = (storeTabIndex && Number(storeTabIndex)) || 0
  const res = await getNavList()
  if (res) {
    appStore.setAppInfo(res)
    // 标准化数据
    navList.value = res.tabs.map((nav: NavListTab) => {
      return {
        id: nav.id,
        title: nav.title,
        active: false,
        hover: false
      }
    })
    stockInfo.value = { code: res.stock.stock_code, name: res.stock.stock_name }
    navList.value[Number(tabIndex)].active = true
    localNavList.value = Array.from(navList.value)
    // 设置store
    usePanelStore().setPanel(navList.value[tabIndex])
    preNavListTab.value = navList.value[tabIndex]
    pageChangeEventBus.emit({ ...navList.value[tabIndex], first: true })
  }
}
setNavListData()

onMounted(() => {
  setDragTabVm()
})

// 交互：创建拖拽tab实例
function setDragTabVm() {
  sortable.value = new Sortable(navListRef.value, {
    ghostClass: 'nav-ghost',
    chosenClass: 'nav-chosen',
    dragClass: 'nav-drag',
    forceFallback: true,
    animation: 250,
    onEnd: async function (evt: SortableEvent) {
      const { oldIndex, newIndex } = evt
      moveArrayElement(localNavList.value, oldIndex || 0, newIndex || 0)

      const tabs = localNavList.value.map((nav) => nav.id)
      try {
        await updateNavList(appStore.appInfo!.id, tabs)
      } catch (error) {
        window.f10log(ERRORTYPE.AJAX, `导航排序失败：${error}`, error)
        ElMessage.error('操作失败！')
      }
    },
    onStart: function (evt: SortableEvent) {
      window.weblog.report({
        id: 'thspc_f10_copilot_nav_drag',
        action: 'press',
        logmap: {}
      })
      const { oldIndex } = evt
      const item = localNavList.value[oldIndex || 0]
      selectPage(item)
    }
  })
}

// 交互：重排列表
function moveArrayElement<T>(array: T[], from: number, to: number): T[] {
  if (to >= 0 && to < array.length) {
    array.splice(to, 0, array.splice(from, 1)[0])
  }
  return array
}

// 交互：页面切换
async function selectPage(item: NavListTab, reset?: boolean) {
  if (preNavListTab.value?.id === item.id && !reset) return
  console.log(1);
  
  localStorage.setItem(
    'aif10-tabIndex',
    navList.value.findIndex((nav) => nav.id === item.id).toString()
  )
  
  if (reset) {
    ElMessageBox({
      message: h('span', { class: 'text-base font-semibold' }, '确定将此导航恢复为默认版面吗？'),
      center: true,
      autofocus: false,
      showCancelButton: true,
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      showClose: false,
      customStyle: {
        width: '284px'
      },
      callback: async (action: Action) => {
        if (action === 'confirm') {
          try {
            await resetPanel(item.id)
            ElMessage.success('恢复成功！')
            reloadPage(item)
          } catch (error) {
            window.f10log(ERRORTYPE.AJAX, `重置页面失败：${error}`, error)
            ElMessage.error('重置失败！请稍后重试！')
          }
        }
      }
    })
    return
  }
  reloadPage(item)
}

function reloadPage(item: NavListTab) {
  preNavListTab.value = item
  navList.value.map((nav) => {
    nav.active = nav.id === item.id
  })
  console.log(item);
  // 设置store
  usePanelStore().setPanel(item)
  pageChangeEventBus.emit(item)
}

// 交互：显示工具栏
function showTools(item: NavListTab) {
  item.hover = !item.hover
  navList.value.forEach((navTab) => {
    if (navTab.id !== item.id) {
      navTab.hover = false
    }
  })
}

// 交互：编辑面板
async function editPanelTitle(item: NavListTab) {
  item.edit = true
  item.hover = false
  await nextTick()
  ;(proxy as any)?.$refs[`${item.id}tabInput`]?.[0]?.focus()
}

// 交互：保存面板标题
async function savePanelTitle(event: Event, item: NavListTab) {
  item.edit = false
  const value = (event.target as HTMLInputElement).value

  if (!value) {
    ElMessage.error('标题不能为空！')
    return
  }

  if (value === item.title) {
    return
  }
  try {
    await updatePanelTitle(item.id, value)
    item.title = value
    ElMessage.success('更新成功！')
  } catch (error) {
    ElMessage.error('更新失败！')
  }
}
</script>

<style lang="less" scoped>
.nav-item {
  &:nth-child(n + 8)::after {
    border-top-width: 0px !important;
  }
  &:not(:first-child):not(:nth-child(7n + 1))::after {
    border-left-width: 0px !important;
  }
  &.nav-drag {
    background: #edeef0;
    opacity: 1 !important;
  }
  &.nav-ghost {
    opacity: 0.5;
  }
  &.active {
    background-image: linear-gradient(-45deg, #3f72ff 0%, #8f63ff 100%);
    color: #fff;
    font-weight: 600;
  }
}
.dark {
  .nav-item {
    &.nav-drag {
      background: #60656c;
    }
  }
}
.tab-tool {
  @apply flex justify-center items-center rounded-sm hover:!text-text-04 black:hover:!text-text-04-dark  hover:bg-background-12 black:hover:bg-background-12-dark;
}
</style>
